<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <a href="#/address" class="routerDom">地址</a>
    ｜
    <a href="#/info" class="routerDom">用户信息</a>
    ｜
    <a href="#/login" class="routerDom">登陆页面</a>
    <br />

    <div class="content" style="border: 1px solid #000"></div>
    <script>
      // oop编程：面向对象编程 构造函数编程 -> class
      // hashChange监听 hash值的变化
      class VueRouter {
        constructor({ routes }) {
          this.routes = routes
          //  this.routerDom = document
          this.contentDom = document.querySelector('.content')
          this.init()
        }

        // hashchange hashchange 监听hash值的改变，然后切换路由
        init() {
          // 页面跳转的时候，监听hash值的变化
          window.addEventListener('hashchange', this.render.bind(this))
          // 页面刷新的时候，监听hash值的变化
          window.addEventListener('load', this.render.bind(this))
        }

        render() {
          // 取hash值 address / info
          let pathname = window.location.hash.replace(/\#/g, '')
          console.log('pathname:', pathname)
          const renderArr = this.routes.filter((v) => v.path === pathname)
          this.contentDom.innerHTML = renderArr[0].component
        }
      }

      const arr = [
        {
          path: '/address',
          component: '<div>Address</div>',
        },
        {
          path: '/info',
          component: '<div>info</div>',
        },
        {
          path: '/login',
          component: '<div>login</div>',
        },
      ]

      new VueRouter({
        routes: arr,
      })
    </script>
  </body>
</html>
